package com.cysd.ewmksbs.ui.fragment

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.baidu.ocr.sdk.OCR
import com.baidu.ocr.sdk.OnResultListener
import com.baidu.ocr.sdk.exception.OCRError
import com.baidu.ocr.sdk.model.AccessToken

import com.baidu.ocr.ui.camera.CameraActivity
import com.cszy.ewmxns.base.BaseVMFragment
import com.cszy.ewmxns.ext.launch
import com.cszy.ewmxns.ext.toast
import com.cysd.ewmksbs.ksb_adapter.indexGridAdapter
import com.cysd.ewmksbs.ksb_adapter.indexListAdapter

import com.cysd.ewmksbs.ui.activity.Ksb_CreatQrCodeActivity
import com.cysd.ewmksbs.ui.activity.Ksb_DetailActivity1
import com.cysd.ewmksbs.ui.activity.Ksb_DetailActivity3
import com.cysd.ewmksbs.ui.activity.Ksb_DetailActivity4
import com.cysd.ewmksbs.ui.activity.Ksb_OcrResultActivity
import com.cysd.ewmksbs.ui.activity.Ksb_QrcodeActivity
import com.cysd.ewmksbs.ui.activity.Ksb_SelectChangjingActivity
import com.cysd.ewmksbs.ui.activity.Ksb_TxmScanResultActivity
import com.cysd.ewmksbs.ksb_ui.dialog.FunctionGuideDialog
import com.cysd.ewmksbs.ksb_ui.dialog.PermissoTipDialog
import com.cysd.ewmksbs.ksb_ui.dialog.UserAgreementDialog
import com.cysd.ewmksbs.ksb_ui.dialog.UserRefusedPermissonDialog
import com.cysd.ewmksbs.ksb_utils.FileUtil
import com.cysd.ewmksbs.ksb_utils.SpUtils
import com.cysd.ewmksbs.viewmodel.IndexViewModel
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hlyj.http.base.tool.lib_hlyj_base.Constants
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseModuleSpUtils
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener

import com.hnyyac.ad.mds.utils.BaseAdConstants
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanIntentResult
import com.journeyapps.barcodescanner.ScanOptions
import com.csylhl.ewmksb.databinding.FragmentBlankBinding


class Ksb_IndexFragment : BaseVMFragment<IndexViewModel, FragmentBlankBinding>(),IAdViewListener {
    private var adapter: indexGridAdapter? = null
    private var adapter_list: indexListAdapter? = null
    private var hasGotToken = false
    private var pernissonTopdialog: PermissoTipDialog? = null
    var app_process: String? = "0" //整个应用流程
    var type_proces: String? = null //功能入口类型
    var function_type:String? = null //功能类型
    private var newGromoreFeedAd : NewGroMoreFeedAdManager? =null
    // 通用识别返回
    private val generalBasicLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            launch(Ksb_OcrResultActivity::class.java)
        }
    }
    // 条形码识别返回
    private val barcodeLauncher = registerForActivityResult<ScanOptions, ScanIntentResult>(
        ScanContract()

    ) { result: ScanIntentResult ->
        showLoading("正在识别中，请稍后")
        if (result.contents == null) {
            Toast.makeText(requireActivity(), "已取消", Toast.LENGTH_LONG).show()
            dismissLoading()

        } else {
            var str= result.contents
            var bundle=Bundle()
            bundle.putString("scanResult",str)
            launch(bundle, Ksb_TxmScanResultActivity::class.java)

        }
    }
    override fun initView(savedInstanceState: Bundle?) {
        // 请选择您的初始化方式
        app_process = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)
        if (app_process=="0"){  //黑名单界面
           mBinding.llNotblack.visibility= View.GONE
           mBinding.llBlack.visibility= View.VISIBLE
        }else{//非黑界面
            mBinding.llNotblack.visibility= View.VISIBLE
            mBinding.llBlack.visibility= View.GONE
            mBinding.tvPrivacyId.text=BaseModuleSpUtils.getInstance().getString(Constants.PRIVACYID)
        }
        initAccessToken()
    }

    override fun initData() {
       //获取首页grid数据
        adapter = indexGridAdapter()
        mBinding.recyIndexGrid.layoutManager= GridLayoutManager(requireContext(),2)
        mBinding.recyIndexGrid.adapter=adapter
        adapter?.submitList(mViewModel.getIndexGrid())

        //获取首页黑名单下List列表
        adapter_list = indexListAdapter()
        mBinding.recyIndexBlacklist.layoutManager= LinearLayoutManager(requireContext())
        mBinding.recyIndexBlacklist.adapter=adapter_list
        adapter_list?.submitList(mViewModel.getIndexList())
        //启动流程
        newGromoreFeedAd = NewGroMoreFeedAdManager(requireActivity(), BaseAdConstants.FEEDAD_Id, mBinding?.fragmentContainer,62)
        newGromoreFeedAd?.loadAd()
        when (app_process) {
            "0" -> ""
            "1" -> app_process_1()
            "2" -> app_process_2()
        }
    }
    fun app_process_1() {
        type_proces = "第一次进首页插屏"
        AdManager.loadChapin(
            requireActivity(),
            2,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    Log.e("qin", "首页流程1插屏加载失败")
                    if (!SpUtils.getInstance().getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)){
                        if (!isAdded)return
                        showFunctionGuideDialog(requireActivity())
                    }
                }
            })
    }
    fun app_process_2() {
        type_proces = "第一次进首页插屏"
        AdManager.loadChapin(
            requireActivity(),
            2,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    Log.i("qin", "首页流程2插屏加载失败")
                    if (!SpUtils.getInstance().getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)){
                        showFunctionGuideDialog(requireActivity())
                    }

                }
            })
    }

    /**
     * 显示功能引导弹窗
     */
    private fun showFunctionGuideDialog(context: Context) {
        // 创建对话框实例
        val dialog = FunctionGuideDialog(context)
        dialog.setCancelable(false) // 设置对话框不可取消
        dialog.setOnGuideDialogListener(object : FunctionGuideDialog.onGuideDialogListener {
            override fun btnOnclick() {
                closeFunctionGuideDialog()

            }

            private fun closeFunctionGuideDialog() {
                dialog.dismiss() // 关闭对话框
                // 处理点击引导内容的回调
                type_proces = "功能弹窗"
                AdManager.loadVideo(
                    requireActivity(),
                    4,
                    this@Ksb_IndexFragment,
                    object : AdLoadListener {
                        override fun onAdLoadFailed(ad: IAdView?) {
                            showInterstitialWithAgree()
                        }
                    })
            }

            override fun btnOnclose() {
                closeFunctionGuideDialog()
            }
        })

// 显示对话框
        dialog.show()

    }

    private fun showInterstitialWithAgree() {
        type_proces = "功能弹窗关闭广告"
        AdManager.loadChapin_nocache(requireActivity(), 9, this, object : AdLoadListener {
            override fun onAdLoadFailed(ad: IAdView?) {
                showAgreementtDialog()
            }
        })
    }

    /**
     * 显示隐私协议弹窗
     */
    private fun showAgreementtDialog() {
        if (SpUtils.getInstance().getBoolean(BaseAppConstans.isAgreeMent)) {

            return
        }
        var dialog = UserAgreementDialog(requireActivity())
        dialog!!.show()
        dialog!!.setPrivateId("您好"+"("+ BaseModuleSpUtils.getInstance().getString(Constants.PRIVACYID)+")")
        dialog!!.setCancelable(false)
        dialog!!.setOnAgreementListener(object : UserAgreementDialog.AgreementDialogListner {
            override fun onDialogListener(clickType: Boolean) {
                if (clickType) {
                    SpUtils.getInstance().putBoolean(BaseAppConstans.isAgreeMent, true)
                    if (!SpUtils.getInstance().getBoolean(BaseAppConstans.IS_SHOW_YINSI_CHAPIN)){
                        type_proces="特殊情况点击同意隐私的插屏"
                        AdManager.loadChapin_nocache(
                            requireActivity(),
                            10,
                            this@Ksb_IndexFragment,
                            object : AdLoadListener {
                                override fun onAdLoadFailed(ad: IAdView?) {


                                }
                            })
                    }

                } else { //拒绝隐私协议
                    activity?.finish()

                }
            }
        })
    }
    override fun initListener() {
        //黑名单界面监听--------
//        mBinding.llQrcode.setOnClickListener {
//             function_type="二维码内容"
//            if (XXPermissions.isGranted(requireActivity(), android.Manifest.permission.CAMERA)) {
//                // 监听扫描结果
//                var bundle=Bundle()
//                bundle.putString("type","general")
//                launch(bundle,QrcodeActivity::class.java)
//
//            } else {
//                request_Permission(
//                    requireActivity(),
//                    android.Manifest.permission.CAMERA,
//                    "相机",
//                    "需要获取您的相机权限用来扫描二维码"
//                )
//            }
//
//        }
       //ocr文字识别
        mBinding.llImageToText.setOnClickListener {
            function_type="图片提取文字"
            if (XXPermissions.isGranted(requireActivity(), android.Manifest.permission.CAMERA)) {
                // 监听扫描结果
                openCamera()

            } else {
                request_Permission(
                    requireActivity(),
                    android.Manifest.permission.CAMERA,
                    "相机",
                    "需要获取您的相机权限用来扫描二维码"
                )
            }

        }

        //解析wifi密码
        mBinding.llDecipherWifi.setOnClickListener {
            Ksb_QrcodeActivity.launch(requireActivity(),"wifi")
        }


       //生成二维码
        mBinding.llTextToCode.setOnClickListener {
            Ksb_CreatQrCodeActivity.launch(requireActivity(),1)
        }
        //生成二维码网址生成
        mBinding.llUrl.setOnClickListener {
            Ksb_CreatQrCodeActivity.launch(requireActivity(),3)
        }
        //生成二维码文本生成
        mBinding.llLxr.setOnClickListener {
            Ksb_CreatQrCodeActivity.launch(requireActivity(),2)
        }
        //条形码查价
        mBinding.llQueryShopPrice.setOnClickListener {
            function_type="条形码查价"
            if (XXPermissions.isGranted(requireActivity(), android.Manifest.permission.CAMERA)) {
                // 监听扫描结果
                  startScannerForTxm()

            } else {
                request_Permission(
                    requireActivity(),
                    android.Manifest.permission.CAMERA,
                    "相机",
                    "需要获取您的相机权限用来扫描二维码"
                )
            }
        }
        //wifi二维码解析
        mBinding.llScanCode.setOnClickListener {
            function_type="wifi二维码解析"
            if (XXPermissions.isGranted(requireActivity(), android.Manifest.permission.CAMERA)) {
                Ksb_QrcodeActivity.launch(requireActivity(),"wifi")

            } else {
                request_Permission(
                    requireActivity(),
                    android.Manifest.permission.CAMERA,
                    "相机",
                    "需要获取您的相机权限用来扫描二维码"
                )
            }

        }

       //黑名单下 列表点击监听
        adapter_list?.setOnItemClickListener { adapter, view, position ->
            when(position){
                0,1->{
                    val bundle=Bundle()
                    bundle.putString("type",position.toString())
                    launch(bundle,Ksb_DetailActivity1::class.java)
                }
                2->{
                    launch(Ksb_DetailActivity3::class.java)
                }
                3->{
                    launch(Ksb_DetailActivity4::class.java)
                }
            }
        }

        //非黑界面操作
        mBinding.rvNotblackMain.setOnClickListener {
            launch(Ksb_SelectChangjingActivity::class.java)
            // 调用方法尝试同时展示两个插屏广告
            type_proces="rvNotblackMain"


        }
        //非黑扫二维码
        mBinding.rvSaoma.setOnClickListener {
            Ksb_QrcodeActivity.launch(requireActivity(),"general")
        }
        //非黑生成二维码
        mBinding.rvCreatQrcode.setOnClickListener {
            Ksb_CreatQrCodeActivity.launch(requireActivity())
        }
        //非黑扫码支付
        mBinding.rvSaomaPay.setOnClickListener {
            Ksb_QrcodeActivity.launch(requireActivity(),"general")
        }
        mBinding.tvLookmore.setOnClickListener {
            launch(Ksb_SelectChangjingActivity::class.java)
        }
        adapter?.setOnItemClickListener{adapter, view, position ->
            Ksb_QrcodeActivity.launch(requireActivity(),"general")
        }

    }

    /**
     * 以license文件方式初始化
     */
    private fun initAccessToken() {
        OCR.getInstance(requireActivity())
            .initAccessToken(object : OnResultListener<AccessToken> {
                override fun onResult(accessToken: AccessToken) {
                    val token = accessToken.accessToken
                    hasGotToken = true
                    Log.e("qin", "获取token成功")
                }

                override fun onError(error: OCRError) {
                    error.printStackTrace()
                    Log.e("qin", "获取token失败")
                }
            }, requireActivity().applicationContext)
    }
    private fun openCamera() {
        if (!checkTokenStatus()) {
            return
        }
        // 2. 创建并启动Intent
        val intent = Intent(requireActivity(), CameraActivity::class.java).apply {
            putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile(requireActivity().applicationContext).absolutePath)
            putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL)
        }

        generalBasicLauncher.launch(intent)
    }
    private fun checkTokenStatus(): Boolean {
        if (!hasGotToken) {
            Toast.makeText(requireActivity(), "token还未成功获取", Toast.LENGTH_LONG).show()
        }
        return hasGotToken
    }


    /**
     * 条形码识别启动
     */
    private fun startScannerForTxm() {
        val options = ScanOptions()
        options.setDesiredBarcodeFormats(ScanOptions.ONE_D_CODE_TYPES)
        options.setPrompt("扫描条形码")
        options.setCameraId(0) // 使用设备的特定摄像头
        options.setBeepEnabled(true)
        options.setBarcodeImageEnabled(true)
        options.setOrientationLocked(false)
        barcodeLauncher.launch(options)
    }
    fun request_Permission(
        context: Activity,
        req_permisson: String,
        permisson_name: String,
        content: String
    ) {
        // 检查是否已标记为"不再询问"
        if (!SpUtils.getInstance().getBoolean(permisson_name)) { // 没有获取该权限或者没有永久拒绝
            showPermissonTipsDialog(context, content)
        }
        XXPermissions.with(context)
            // 申请单个权限
            .permission(req_permisson)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (pernissonTopdialog != null) {
                        pernissonTopdialog!!.dismiss()
                    }
                    if (!allGranted) {

                        toast("获取 $permisson_name 权限成功")
                        return
                    }
                    SpUtils.getInstance().putBoolean(permisson_name, true)
                    toast("获取 $permisson_name 权限成功")
                        when(function_type){
                            "二维码内容"->{
                                Ksb_QrcodeActivity.launch(requireActivity(),"general")
                            }
                            "条形码查价"->{
                                startScannerForTxm()
                            }

                            "图片提取文字"->{
                                openCamera()
                            }
                            "wifi二维码解析"->{
                                Ksb_QrcodeActivity.launch(requireActivity(),"wifi")
                            }

                        }




                }

                override fun onDenied(
                    permissions: MutableList<String>,
                    doNotAskAgain: Boolean
                ) {
                    if (doNotAskAgain) {
                        if (pernissonTopdialog != null) {
                            pernissonTopdialog!!.dismiss()
                        }
                        showDoNotAskAgainDialog(
                            requireActivity(),
                            req_permisson,
                            permisson_name
                        )
                    } else {
                        if (pernissonTopdialog != null) {
                            pernissonTopdialog!!.dismiss()
                        }

                    }
                }
            })
    }
    /**
     * 用户单次拒绝
     */
    fun showPermissonTipsDialog(context: Context, content: String) {
        pernissonTopdialog = PermissoTipDialog(context)
        pernissonTopdialog!!.setPermissionMessage(content)
        pernissonTopdialog!!.show()
        pernissonTopdialog!!.setCancelable(false)
    }
    /**
     * 用户多次拒绝
     */
    fun showDoNotAskAgainDialog(context: Context, permission: String, permissionName: String) {
        var dialog = UserRefusedPermissonDialog(context,permission)
        dialog.setPermissionMessage("您未授予 $permissionName 权限，请去设置中开启")
        dialog.setCancelable(false)
        dialog.show()
    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {
        when(type_proces){
            "功能返回插屏"->{
                SpUtils.getInstance().putBoolean(BaseAppConstans.IS_SHOW_YINSI_CHAPIN,true)//已经弹过了功能返回的插屏
            }

            "功能弹窗" ->{
                SpUtils.getInstance().putBoolean(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG,true)
            }
        }
    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
        // 检查 Fragment 是否仍然有效
        if (!isAdded || isDetached || activity == null) {
            return // 如果 Fragment 无效，直接返回
        }
        when(type_proces){
            "第一次进首页插屏"->{
               // Log.e("qin","第一次进首页插屏执行了吗")
                if (!SpUtils.getInstance().getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)){
                    showFunctionGuideDialog(requireActivity())
                }else{
                    if (!SpUtils.getInstance().getBoolean(BaseAppConstans.isAgreeMent)) {
                        showAgreementtDialog()
                    }
                }
            }


            "功能弹窗关闭广告" -> {
                if (app_process == "1") {
                    showAgreementtDialog()
                }
            }
            "功能弹窗" -> {
                if (app_process == "1") {
                    showInterstitialWithAgree()
                }
            }

           "rvNotblackMain"->{
               Log.e("qin11","关闭rvNotblackMain执行了吗")
           }






        }
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }
}